/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.mapper.BaseMapper;
import org.jbase.admin.dao.AdminUserDao;
import org.jbase.admin.dao.AdminUserRoleDao;
import org.jbase.admin.entity.AdminRole;
import org.jbase.admin.entity.AdminUser;
import org.jbase.admin.entity.AdminUserRole;
import org.jbase.common.service.EntityMapperService;
import org.jbase.common.utils.Encodes;
import org.jbase.common.utils.Pager;
import org.jbase.common.utils.message.Message;
import org.jbase.common.utils.message.MessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project: jbase-springboot <br/>
 * File: AdminUserService.java <br/>
 * Class: org.jbase.admin.service.AdminUserService <br/>
 * Description: 管理员. <br/>
 * Copyright: Copyright (c) 2016 <br/>
 * Company: http://git.oschina.net/liuzp315/Jbase <br/>
 * Makedate: 2016-12-25 01:03:08 <br/>
 * gen by Jbase Coder <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
@Service
public class AdminUserService extends EntityMapperService<AdminUser> {

	@Autowired
	private AdminUserDao adminUserDao;

	@Autowired
	private AdminUserRoleDao adminUserRoleDao;

	@Autowired
	private AdminRoleService adminRoleService;

	@Override
	public BaseMapper<AdminUser> dao() {
		return adminUserDao;
	}

	public Pager query(Map<String, String> map, Pager pager) {

		PageQuery<Object> pageQuery = new PageQuery<Object>(pager.getPageNumber(), map, -1, pager.getPageSize());
		adminUserDao.selectPager(pageQuery);

		pager.setList(pageQuery.getList());
		pager.setRecordCount((int) pageQuery.getTotalRow());
		return pager;
	}

	public AdminUser fetchBySid(String sid) {
		return adminUserDao.fetchBySid(sid);
	}

	public void deleteBySid(String sid) {
		adminUserDao.deleteBySid(sid);
	}

	public Message<List<AdminUser>> listBySids(String sids) {
		Message<List<AdminUser>> mess = new Message<>();
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);

		if (StringUtils.isBlank(sids)) {
			return mess;
		}

		if (sids.startsWith(",")) {
			sids = sids.substring(1);
		}

		List<String> sqltemp = new ArrayList<>();
		String[] split = sids.split(",");
		for (String str : split) {
			if (StringUtils.isNotBlank(str))
				sqltemp.add(str);
		}

		Map<String, Object> param = new HashMap<>();
		param.put("sids", sqltemp);
		List<AdminUser> listBySids = adminUserDao.listBySids(param);

		mess.setData(listBySids);

		return mess;
	}

	@Override
	public Message<AdminUser> doInsert(Map<String, Object> map) {
		map.put("password", Encodes.md5(map.get("password").toString()));
		AdminUser au = map2entity(map, new AdminUser());
		insertUserRole(map.get("roleSids"), au);
		return insert(au);
	}

	@Override
	public Message<AdminUser> doUpdate(Map<String, Object> map, String entityId) {
		AdminUser au = map2entity(map, unique(entityId).getData());

		adminUserRoleDao.deleteByUserSid(au.getSid());
		insertUserRole(map.get("roleSids"), au);

		return updateById(au);
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param rsids
	 * @param au
	 */
	private void insertUserRole(Object rsids, AdminUser au) {
		if (rsids != null && StringUtils.isNotBlank(rsids.toString())) {
			List<AdminUserRole> list = new ArrayList<>();
			List<AdminRole> listBySids = adminRoleService.listBySids(rsids.toString()).getData();
			for (AdminRole adminRole : listBySids) {
				AdminUserRole aur = new AdminUserRole();
				aur.setRoleId(adminRole.getId());
				aur.setRoleSid(adminRole.getSid());
				aur.setRoleName(adminRole.getName());
				aur.setUserId(au.getId());
				aur.setUserSid(au.getSid());
				aur.setUserName(au.getName());
				list.add(aur);
			}
			sql.insertBatch(AdminUserRole.class, list);
		}
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param baseUserName
	 * @return
	 */
	public boolean checkName(String name) {
		AdminUser bs = adminUserDao.fetchByName(name);
		return bs == null;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param baseUserName
	 * @param usid
	 * @return
	 */
	public boolean checkNameNotMe(String name, String usid) {
		AdminUser bs = adminUserDao.fetchByNameNotMe(name, usid);
		return bs == null;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param sid
	 * @param n_password
	 * @return
	 */
	public Message<AdminUser> modifyPassword(String sid, String password) {
		Message<AdminUser> mess = new Message<>();
		mess.SetMessageCode(MessageCode.FAIL);
		adminUserDao.updatePassword(Encodes.md5(password), sid);
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);
		return mess;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param currentUsername
	 * @return
	 */
	public AdminUser fetchByName(String currentUsername) {
		return adminUserDao.fetchByName(currentUsername);
	}

	@Override
	public Message<Integer> deleteById(Object key) {
		AdminUser au = adminUserDao.unique(key);
		adminUserRoleDao.deleteByUserSid(au.getSid());
		return super.deleteById(key);
	}
}
